/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package DataSource;

import java.util.Vector;

/**
 *
 * @author Tuan
 */
public abstract class PublisherImpl implements Publisher{

    protected Vector subscribers;
    
    public PublisherImpl(){
        subscribers = new Vector();
    }
    
    public boolean addSubscriber(Subscriber sub) {
        try{
            this.subscribers.addElement(sub);
            return true;
        } catch(Exception e){
            return false;
        }
    }

    public synchronized void notifySubscribers(final Data data) {
        for(int i = 0; i < this.subscribers.size(); i++){
            final Subscriber sub = (Subscriber)subscribers.elementAt(i);            
            Thread myThread = new Thread(new Runnable() {

                public void run() {
                    sub.update(data);
                }
            });
            myThread.start();
        }
    }

    public synchronized boolean removeSubscriber(Subscriber sub) {
        //Could be wrong if reference is different!
        try{
            if(this.subscribers.contains(sub)){
                this.subscribers.removeElement(sub);
                return true;
            }
            return false;
        } catch(Exception e){
            return false;
        }        
    }
    
}
